package com.zzzzzz.sys.city;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.zzzzzz.core.datagrid.BaseData;
import com.zzzzzz.plugins.shiro.I;
import com.zzzzzz.utils.DateTimeUtils;

@Service
public class CityService {
	@Resource
	public CityDao cityDao;

	@Transactional
	public int save(City city, I i) {
		city.setUpdDt(new Date());
		city.setUpdBy(i.getId());
		if (city.getId() == null) {
			city.setAddDt(new Date());
			city.setAddBy(i.getId());
			cityDao.add(city);
		} else {
			cityDao.updById(city);
		}
		//Map<String, List<City>> cityMap=getAllCityMap();
		return 1;
	}
	
	/**
	 * 此处调用getAllCityMap先获取所有城市列表。
	 * @param cd
	 * @return
	 */
	public City getCityByCd(String cd) {
		Map<String, City> allCityMap = cityDao.getAllCityMap();
		City city = allCityMap.get(cd);
		return city;
	}
  	@Transactional
		public List<BaseData> batchAdd(List<City> list, I i) {
			logger.info("city batchAdd validate start:" + DateTimeUtils.date2Str(new Date(), DateTimeUtils.FORMAT_YYYY_MM_DD_HH_MM_SS));
			//start validate
			int errTt = 0;// 错误信息条数
			int susTt = 0;// 正确信息条数
			BaseData baseData;
			//用于存放信息
			List<BaseData> listMsg=new ArrayList<BaseData>();
			for (City city : list) {
				//验证是否为空值
				if(StringUtils.isBlank(city.getCd())){
					baseData=new BaseData();
					baseData.setErrMsg("代码"+city.getCd()+"为无效值");
					listMsg.add(baseData);
					errTt++;
				}else{									
						//如果没存在就导入
						city.setSt(0);
						city.setSortNb(1);
						if(city.getDescr()==null||city.getDescr().equals("")){
							city.setDescr(null);
						}
						if(city.getProvince()==null||city.getProvince().equals("")){
							city.setProvince(null);
						}
						try{
							save(city, i);
							susTt++;
						}catch(DuplicateKeyException e){
							baseData=new BaseData("-1", String.format("城市代码"+city.getCd()+"已经存在"));
							listMsg.add(baseData);
							errTt++;
						}
						
					}
			}
			baseData = new BaseData();
			baseData.setErrMsg("总共有" + (susTt + errTt) + "行记录；共有" + susTt+ "行记录导入成功；共有" + errTt + "行记录导入失败；");
			listMsg.add(baseData);
			logger.info("city batchAdd save end:" + DateTimeUtils.date2Str(new Date(), DateTimeUtils.FORMAT_YYYY_MM_DD_HH_MM_SS));
			return listMsg;
		}
	
	private static final Logger logger = LoggerFactory.getLogger(City.class);
}
